/*!
	@file
	@author		George Evmenov
	@date		07/2009
*/

#include "MyGUI_OpenGLVertexBuffer.h"
#include "MyGUI_VertexData.h"
#include "MyGUI_OpenGLDiagnostic.h"


namespace MyGUI
{

	const size_t VERTEX_IN_QUAD = 6;
	const size_t RENDER_ITEM_STEEP_REALLOCK = 5 * VERTEX_IN_QUAD;

	OpenGLVertexBuffer::OpenGLVertexBuffer() :
		mNeedVertexCount(0),
		mVertexCount(RENDER_ITEM_STEEP_REALLOCK)
	{
		mpBuffer.clear();
	}

	OpenGLVertexBuffer::~OpenGLVertexBuffer()
	{
		destroy();
	}

	void OpenGLVertexBuffer::setVertexCount(size_t _count)
	{
		if (_count != mNeedVertexCount)
		{
			mNeedVertexCount = _count;
			destroy();
			create();
		}
	}

	size_t OpenGLVertexBuffer::getVertexCount()
	{
		return mNeedVertexCount;
	}

	Vertex* OpenGLVertexBuffer::lock()
	{
		//MYGUI_PLATFORM_ASSERT(mBufferID, "Vertex buffer in not created");

		//// Use glMapBuffer
		//glBindBufferARB(GL_ARRAY_BUFFER_ARB, mBufferID);

		//// Discard the buffer
		//glBufferDataARB(GL_ARRAY_BUFFER_ARB, mSizeInBytes, 0, GL_STREAM_DRAW_ARB);


		//Vertex* pBuffer = (Vertex*)glMapBufferARB(GL_ARRAY_BUFFER_ARB, GL_WRITE_ONLY_ARB);

		//MYGUI_PLATFORM_ASSERT(pBuffer, "Error lock vertex buffer");

		//glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);

		//return pBuffer;

		if (mpBuffer.empty())
			return NULL;

		return getBuffer();
	}

	void OpenGLVertexBuffer::unlock()
	{
		/*MYGUI_PLATFORM_ASSERT(mBufferID, "Vertex buffer in not created");

		glBindBufferARB(GL_ARRAY_BUFFER_ARB, mBufferID);
		GLboolean result = glUnmapBufferARB(GL_ARRAY_BUFFER_ARB);
		glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);

		MYGUI_PLATFORM_ASSERT(result, "Error unlock vertex buffer");*/
	}

	void OpenGLVertexBuffer::destroy()
	{
		mpBuffer.clear();

		//if (mpBuffer)
		//{
		//	delete mpBuffer;
		//	mpBuffer = nullptr;
		//}
	}

	bool OpenGLVertexBuffer::create()
	{
		//MYGUI_PLATFORM_ASSERT(!mBufferID, "Vertex buffer already exist");

		//mSizeInBytes = mNeedVertexCount * sizeof(MyGUI::Vertex);
		////void* data = 0;
		//m_pData = new unsigned char[mSizeInBytes];

		//glGenBuffers(1, &mBufferID);
		//glBindBuffer(GL_ARRAY_BUFFER, mBufferID);
		//glBufferData(GL_ARRAY_BUFFER, mSizeInBytes, m_pData, GL_DYNAMIC_DRAW);

		//// check data size in VBO is same as input array, if not return 0 and delete VBO
		//int bufferSize = 0;
		//glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &bufferSize);
		//if (mSizeInBytes != bufferSize)
		//{
		//	destroy();
		//	MYGUI_PLATFORM_EXCEPT("Data size is mismatch with input array");
		//}

		//glBindBuffer(GL_ARRAY_BUFFER, 0);

		if (mNeedVertexCount == 0)
			return false;

		mpBuffer.resize(mNeedVertexCount);
		//memset(&mpBuffer[0], 0, mNeedVertexCount*sizeof(Vertex));
		return true;


		//mpBuffer = new Vertex[mNeedVertexCount];
		//memset(mpBuffer,0,mNeedVertexCount*sizeof(Vertex));
		//if (mpBuffer) return true;
		//return false;
	}

} // namespace MyGUI
